import { Injectable } from '@nestjs/common';
import sequelize from '../../database/sequelize';
import * as Sequelize from 'sequelize';
import { encryptPassword, makeSalt } from '../../utils/cryptogram';
import { omit } from 'lodash';
@Injectable()
export class UserService {
    /**
     * 查询是否有该用户
     * @param username 
     * @returns
     */
    async findOne(username: string): Promise<any | undefined> {
        const sql = `
        SELECT
            user_id userId, account_name username, real_name realName, passwd password, passwd_salt salt, mobile, role
        FROM
            admin_user
        WHERE
            account_name = '${username}'
        `
        try {
            const user = (
                await sequelize.query(sql, {
                    type: Sequelize.QueryTypes.SELECT,
                    raw: true,
                    logging: false,
                })
            )[0]
            return user
        } catch (error) {
            console.error(error);
            return void 0;
        }
    }

    /**
     * register
     * @param requestBody 
     * @returns
     */
    async register(requestBody: any): Promise<any> {
        const { accountname, realname, password, repassword, mobile } = requestBody
        if (password !== repassword) {
            return {
                code: 400,
                message: '两次密码输入不一致'
            }
        }
        const user = await this.findOne(accountname)
        if (user) {
            return {
                code: 400,
                message: '用户已存在'
            }
        }

        const salt = makeSalt();
        const hashPwd = encryptPassword(password, salt)
        const registerSQL = `
        INSERT INTO admin_user
            (account_name, real_name, passwd, passwd_salt, mobile, user_status, role, create_by)
        VALUES
            ('${accountname}', '${realname}', '${hashPwd}', '${salt}', '${mobile}', 1, 3, 0)
        `
        try {
            await sequelize.query(registerSQL, {logging: false})
            return {
                code: 200,
                message: 'success'
            }
        } catch (error) {
            return {
                code: 503,
                message: `Service error: ${error}`
            }
        }
    }

    async getMyInfo(req: any): Promise<any> {   
        let user = await this.findOne(req.user.username)     // requestBody = requestBody.join('.')
        user = omit(user, ['password', 'salt'])
        return {
            code: 200,
            data: user
        }
    }
}
